#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color
BOLD='\033[1m'

# 动画函数
spinner() {
    local pid=$1
    local delay=0.1
    local spinstr='|/-\'
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf "\r[%c] ${CYAN}%s${NC}" "$spinstr" "$2"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
    done
    printf "\r${GREEN}[✓]${NC} ${CYAN}%s${NC}\n" "$2"
}

# 进度条函数
progress_bar() {
    local duration=$1
    local message=$2
    local elapsed=0
    local width=50
    
    while [ $elapsed -lt $duration ]; do
        local progress=$((elapsed * width / duration))
        local remaining=$((width - progress))
        
        printf "\r${YELLOW}[${NC}"
        printf "%${progress}s" "" | tr ' ' '█'
        printf "%${remaining}s" "" | tr ' ' '.'
        printf "${YELLOW}]${NC} ${CYAN}%s${NC}" "$message"
        
        elapsed=$((elapsed + 1))
        sleep 0.1
    done
    printf "\n"
}

# ASCII艺术标题
print_title() {
    echo -e "${PURPLE}"
    echo '    ____  ____  ____  ____  ____________     _________  _______________  __  ___'
    echo '   / __ \/ __ \/ __ \/ __ \/ ____/ ___/    / ___/ __ \/ ___/_  __/ _ \/  |/  /'
    echo '  / /_/ / /_/ / / / / / / / /    \__ \     \__ \/ / / /\__ \ / / / /_/ / /|_/ / '
    echo ' / ____/ _, _/ /_/ / /_/ / /___ ___/ /    ___/ / /_/ /___/ // / / _, _/ /  / /  '
    echo '/_/   /_/ |_|\____/\____/\____//____/    /____/\____//____//_/ /_/ |_/_/  /_/   '
    echo -e "${NC}"
    echo -e "${YELLOW}================= 欢迎使用判题系统安装程序 ==================${NC}\n"
}

# 打印分隔线
print_separator() {
    echo -e "\n${YELLOW}================================================================${NC}\n"
}

# 打印状态消息
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[成功]${NC} $1"
}

print_error() {
    echo -e "${RED}[错误]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

# 清屏并显示标题
clear
print_title

# 检查操作系统类型
OS="unknown"
print_status "正在检测系统环境..."
if [ "$(uname)" == "Darwin" ]; then
    OS="macOS"
    print_success "检测到操作系统: ${BOLD}macOS${NC}"
elif [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    print_success "检测到操作系统: ${BOLD}$OS${NC}"
else
    print_error "无法检测操作系统类型"
    exit 1
fi

print_separator

# macOS特定的安装
if [ "$OS" == "macOS" ]; then
    print_status "配置macOS环境..."
    
    # 检查是否安装了Homebrew
    if ! command -v brew &> /dev/null; then
        print_warning "未检测到Homebrew,正在安装..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" &
        spinner $! "安装Homebrew"
    fi
    
    # 安装必要的依赖
    print_status "正在安装必要的依赖..."
    (brew update) &
    spinner $! "更新Homebrew"
    
    dependencies=(cmake boost pkg-config python3 openjdk wget git ninja)
    for dep in "${dependencies[@]}"; do
        (brew install $dep) &
        spinner $! "安装 $dep"
    done

    # 安装和链接Python3
    (brew link python3) &
    spinner $! "配置Python3"

    # 设置Java环境变量
    print_status "配置Java环境..."
    echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.zshrc
    echo 'export CPPFLAGS="-I/opt/homebrew/opt/openjdk/include"' >> ~/.zshrc
    
    # 创建工作目录
    INSTALL_DIR="$HOME/judger"
    mkdir -p $INSTALL_DIR
    cd $INSTALL_DIR

else
    # Linux系统检查
    if [ "$EUID" -ne 0 ]; then 
        print_error "在Linux系统上需要root权限运行此脚本"
        exit 1
    fi

    # 设置错误时退出
    set -e

    # Linux系统的安装流程
    print_status "正在安装系统依赖..."
    if [[ "$OS" == "Ubuntu" ]] || [[ "$OS" == "Debian" ]]; then
        (apt-get update) &
        spinner $! "更新软件源"
        
        dependencies=(build-essential cmake git libseccomp-dev libcap-dev libboost-all-dev pkg-config python3 python3-pip default-jdk wget unzip)
        for dep in "${dependencies[@]}"; do
            (apt-get install -y $dep) &
            spinner $! "安装 $dep"
        done
    elif [[ "$OS" == "CentOS Linux" ]] || [[ "$OS" == "Red Hat Enterprise Linux" ]]; then
        (yum update -y) &
        spinner $! "更新软件源"
        
        (yum groupinstall -y "Development Tools") &
        spinner $! "安装开发工具"
        
        dependencies=(cmake git libseccomp-devel libcap-devel boost-devel python3 python3-pip java-latest-openjdk-devel wget unzip)
        for dep in "${dependencies[@]}"; do
            (yum install -y $dep) &
            spinner $! "安装 $dep"
        done
    else
        print_error "不支持的Linux发行版: $OS"
        exit 1
    fi

    # 创建工作目录
    INSTALL_DIR="/opt/judger"
    mkdir -p $INSTALL_DIR
    cd $INSTALL_DIR
fi

print_separator

# 克隆项目代码
print_status "正在克隆项目代码..."
if [ ! -d "judgeV2" ]; then
    (git clone https://github.com/x_wq3337/online-judge.git) &
    spinner $! "克隆代码仓库"
fi
cd online-judge/judgeV2

# 安装第三方依赖
print_status "正在安装第三方依赖..."
# spdlog
if [ ! -d "third_party/spdlog" ]; then
    progress_bar 10 "配置spdlog"
    mkdir -p third_party
    cd third_party
    (git clone https://github.com/gabime/spdlog.git) &
    spinner $! "克隆spdlog"
    cd spdlog
    mkdir build && cd build
    (cmake .. && make -j$(sysctl -n hw.ncpu 2>/dev/null || nproc)) &
    spinner $! "编译spdlog"
    if [ "$OS" == "macOS" ]; then
        (sudo make install) &
        spinner $! "安装spdlog"
    else
        (make install) &
        spinner $! "安装spdlog"
    fi
    cd ../../..
fi

# nlohmann/json
if [ ! -d "third_party/json" ]; then
    progress_bar 10 "配置JSON库"
    mkdir -p third_party
    cd third_party
    (git clone https://github.com/nlohmann/json.git) &
    spinner $! "克隆JSON库"
    cd json
    mkdir build && cd build
    (cmake .. && make -j$(sysctl -n hw.ncpu 2>/dev/null || nproc)) &
    spinner $! "编译JSON库"
    if [ "$OS" == "macOS" ]; then
        (sudo make install) &
        spinner $! "安装JSON库"
    else
        (make install) &
        spinner $! "安装JSON库"
    fi
    cd ../../..
fi

# 创建构建目录并编译
print_status "正在编译项目..."
mkdir -p build
cd build
(cmake ..) &
spinner $! "配置CMake"
(make -j$(sysctl -n hw.ncpu 2>/dev/null || nproc)) &
spinner $! "编译项目"

if [ "$OS" != "macOS" ]; then
    # Linux特定的系统配置
    print_status "正在配置Linux系统..."
    
    progress_bar 5 "创建系统用户"
    # 创建评测用户和组
    groupadd -f judge
    useradd -M -g judge judge 2>/dev/null || true
    
    # 设置必要的目录权限
    chmod 755 $INSTALL_DIR
    chown -R judge:judge $INSTALL_DIR
    
    print_status "配置系统限制..."
    # 配置系统限制
    cat > /etc/security/limits.d/99-judge.conf << EOF
judge soft nproc 1000
judge hard nproc 1500
judge soft nofile 100000
judge hard nofile 100000
EOF
    
    # 配置系统参数
    cat > /etc/sysctl.d/99-judge.conf << EOF
kernel.pid_max=100000
kernel.threads-max=100000
fs.file-max=100000
EOF
    
    # 应用系统参数
    (sysctl --system) &
    spinner $! "应用系统参数"
    
    # 创建日志目录
    mkdir -p /var/log/judge
    chown judge:judge /var/log/judge
else
    # macOS特定的配置
    print_status "正在配置macOS系统..."
    
    # 创建日志目录
    mkdir -p $HOME/Library/Logs/judge
    
    print_status "配置系统限制..."
    # 设置ulimit（仅当前会话）
    ulimit -n 100000
    
    # 添加持久的ulimit设置
    if [ -f ~/.zshrc ]; then
        echo "ulimit -n 100000" >> ~/.zshrc
    fi
    if [ -f ~/.bash_profile ]; then
        echo "ulimit -n 100000" >> ~/.bash_profile
    fi
fi

print_separator

echo -e "${GREEN}${BOLD}安装完成！${NC}"
echo -e "${CYAN}判题系统已安装在: ${BOLD}$INSTALL_DIR${NC}"
if [ "$OS" == "macOS" ]; then
    echo -e "${CYAN}日志文件位置: ${BOLD}$HOME/Library/Logs/judge${NC}"
    print_warning "某些沙箱功能在macOS上可能受限"
else
    print_status "请检查配置文件并根据需要调整参数"
fi

# 打印完成的ASCII艺术
echo -e "${GREEN}"
echo '  ____                   _ '
echo ' |  _ \  ___  _ __   __| |'
echo ' | | | |/ _ \| '\''_ \ / _` |'
echo ' | |_| | (_) | | | | (_| |'
echo ' |____/ \___/|_| |_|\__,_|'
echo -e "${NC}" 